import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import clsx from 'clsx';
import { DrawMode } from '@ttfn/mapbox-gl-draw';
import type { IMaterialProps, IMaterialRecord, IMaterialRef } from './types';
import './material-list.less';

export const MaterialList = forwardRef<IMaterialRef, IMaterialProps>((props, ref) => {
  const { items, map } = props;
  const [selectedIndex, setSelectedIndex] = useState(0);

  const selectItem = (index: number) => {
    const item = items[index];
    if (item) props.command({ id: item.key, class: item.className });
  };

  const upHandler = () => {
    setSelectedIndex((selectedIndex + items.length - 1) % items.length);
  };

  const downHandler = () => {
    setSelectedIndex((selectedIndex + 1) % items.length);
  };

  const enterHandler = () => {
    selectItem(selectedIndex);
    map.draw.setStatus('enable');
    map.draw.changeMode(items[selectedIndex].key as DrawMode);
  };

  const onItemClick = (key: IMaterialRecord['key']) => {
    const index = items.findIndex((v) => v.key === key);
    setSelectedIndex(index);
    selectItem(index);
    map.draw.setStatus('enable');
    map.draw.changeMode(items[selectedIndex].key as DrawMode);
  };

  useEffect(() => setSelectedIndex(0), [items]);

  useImperativeHandle(ref, () => ({
    onKeyDown: ({ event }) => {
      if (event.key === 'ArrowUp') {
        upHandler();
        return true;
      }

      if (event.key === 'ArrowDown') {
        downHandler();
        return true;
      }

      if (event.key === 'Enter') {
        enterHandler();
        return true;
      }

      return false;
    },
  }));

  return (
    <div className="material-dropdown-menu smap-dropdown">
      {items.length ? (
        <>
          <div className="material-group-title">绘制工具</div>
          {items.map(({ key, content, icon, desc = '' }, index) => {
            return (
              <div key={key} onClick={() => onItemClick(key)} className={clsx(`material-item`, { active: selectedIndex === index })}>
                <div className="material-icon">{icon}</div>
                <div className="material-content">
                  <div className="smap-ellipsis content">{content}</div>
                  <div className="smap-ellipsis desc">{desc}</div>
                </div>
              </div>
            );
          })}
        </>
      ) : (
        <div className="item">No result</div>
      )}
    </div>
  );
});
